<template>
  <el-dialog class="enternetValueOpen" :visible.sync="visible" title="" :close-on-click-modal="false">
    <div slot="title">
      <span class="tit">录入净值</span>
      <span style="padding-left: 20px;">{{dataFrom.strategyNetWorthStyle?'复利':'单利'}}</span>
      <span style="padding-left: 4px;font-size:11px;color:#999;">(*可通过策略编辑更改)</span>
    </div>
    <p class="tips">当前最新净值日期：<span>{{dataFrom.networthTime}}</span> <span style="padding-left: 10px;">{{dataFrom.networth}}</span> </p>
    <el-radio-group v-model="type" size="mini">
      <el-radio-button label="手动录入"></el-radio-button>
      <el-radio-button label="模板导入"></el-radio-button>
      <el-radio-button label="文本粘贴"></el-radio-button>
    </el-radio-group>
    <div v-if="type=='手动录入'">
      <div class="addNetworth-line" v-for="(item, i) in networthValueList" :key="i">
        <span>净值时间：</span>
        <el-date-picker :class="{'error-border': errorList.indexOf(i)!=-1 && !item.networthTime}" v-model="item.networthTime" 
          :picker-options="pickerOptions" size="mini" type="date" value-format="yyyy-MM-dd" style="width: 140px;">
        </el-date-picker>
        <span style="padding-left: 20px;">净值：</span><el-input-number :class="{'error-border': errorList.indexOf(i)!=-1 && !item.networthValue }" v-model="item.networthValue" size="mini" :precision="4" style="width: 160px;" :controls="false"></el-input-number>
        <i v-if="i" class="el-icon-close" @click="closeNetworthHandle(i)"></i>
        <i :style="i?'':'margin-left: 20px;'" class="el-icon-plus" @click="addNetworthHandle(i)"></i>
      </div>
    </div>
    <div v-if="type=='模板导入'">
      <el-button class="bg-green search-box" size="small" @click="downloadHandle">下载模板</el-button>
      <el-upload
        style="display: inline-block;margin-left: 10px;"
        action="hh"
        :before-upload="beforeUpload">
        <el-button type="primary" size="small">导入净值</el-button>
      </el-upload>
    </div>
    <div class="txtChunk" v-if="type=='文本粘贴'">
      <div class="txt-chunk">
        <span>净值日期 单位净值</span>
        <el-input
          type="textarea"
          :rows="20"
          :placeholder="txts_tips"
          v-model="dates">
        </el-input>
      </div>
      <!-- <div class="txt-chunk">
        <span>累计净值</span>
        <el-input
          type="textarea"
          :rows="20"
          placeholder="请输入累计净值"
          v-model="txts">
        </el-input>
      </div> -->
    </div>
    <div v-if="type!='模板导入'" slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="type=='手动录入'?submit():txtSubmit()">提交</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { addOrUpdateNetWorth, upload, download, addNetWorthByText } from '@/api/policyManage'
// import { isDate } from '@/utils'

export default {
  data() {
    return {
      type: '手动录入',
      visible: false,
      detailId: '',
      investId: '',
      strategyId: '',
      errorList: [],
      dataFrom: {},
      networthValueList: [
        { times: new Date().getTime(), networthValue: undefined, networthTime: '' }
      ],
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        }
      },
      txts: '',
      dates: '',

      txts_tips: '2021/05/30	1.0000  \n2021/05/31	1.2000 '
    }
  },
  methods: {
    init(row) {
      this.dates = ''
      this.dataFrom = Object.assign({}, row)
      this.visible = true
      this.dataFrom.strategyNetWorthStyle = this.dataFrom.strategyNetWorthStyle!=null ? this.dataFrom.strategyNetWorthStyle : 1
      this.networthValueList = [
        { times: new Date().getTime(), networthValue: undefined, networthTime: '' }
      ]
    },
    closeNetworthHandle(i) {
      this.networthValueList.splice(i, 1)
    },
    addNetworthHandle(i) {
      this.networthValueList.splice(i+1, 0, {
        times: new Date().getTime(), networthValue: undefined, networthTime: ''
      })
    },
    downloadHandle() {
      download().then((res) => {
        const content = res
        const blob = new Blob([content])
        const fileName = '净值导入模板.xlsx'
        if ('download' in document.createElement('a')) { // 非IE下载
          const elink = document.createElement('a')
          elink.download = fileName
          elink.style.display = 'none'
          elink.href = URL.createObjectURL(blob)
          document.body.appendChild(elink)
          elink.click()
          URL.revokeObjectURL(elink.href) // 释放URL 对象
          document.body.removeChild(elink)
        } else { // IE10+下载
          navigator.msSaveBlob(blob, fileName)
        }
      })
    },
    beforeUpload(file) {
      const fd = new FormData()
      fd.append('file', file)
      fd.append('strategyId', this.dataFrom.strategyId)
      fd.append('strategyName', this.dataFrom.strategyName)
      fd.append('investName', this.dataFrom.investName)
      fd.append('userId', this.dataFrom.userId)
      fd.append('strategyNetWorthStyle', this.dataFrom.strategyNetWorthStyle)
      upload(fd).then((res) => {
        this.$notify({
          message: res.msg,
          type: res.code ? 'error' : 'success',
          duration: 3 * 1000
        })
        this.visible = false
        this.$emit('closeOpen')
      })
      return false
    },
    submit() {
      this.errorList = []
      this.networthValueList.map((item, i) => {
        if(!item.networthValue || !item.networthTime) {
          this.errorList.push(i)
        }
      })
      if(this.errorList.length) {
        this.$message({
          message: '部分净值录入不完整',
          type: 'warning',
          duration: 2000
        })
        return
      }
      addOrUpdateNetWorth({
        ...this.dataFrom,
        networthValueList: this.networthValueList
      }).then(res => {
        if(res.code == 0) {
          this.$notify({
            message: res.msg,
            type: 'success',
            duration: 2000
          })
          this.visible = false
          this.$emit('closeOpen')
        }
      })
    },
    txtSubmit() {
      const new_dates = []
      const new_txts = []
      const line = this.dates.split(/[\n]/)
      
      line.map(items => {
        if(items) {
          try {
            new_dates.push((items.split(/[\t]/)[0]).trim())
          } catch (error) {
            this.$message({
              message: '输入格式有误',
              type: 'error'
            })
          }
          try {
            new_txts.push((items.split(/[\t]/)[1]).trim())
          } catch (error) {
            this.$message({
              message: '输入格式有误',
              type: 'error'
            })
          }
        }
      })
      // const txts = this.txts.split(/[\n]/)
      // const new_dates = []
      // const new_txts = []
      // dates.map((date) => {
      //   if(isDate(date)) {
      //     new_dates.push(date)
      //   }
      // })
      // txts.map((txt) => {
      //   if(Number(txt)||Number(txt)==0) {
      //     new_txts.push(txt.trim())
      //   }
      // })
      // if(new_txts.length>new_dates.length) new_txts.splice(new_dates.length, new_txts.length)
      addNetWorthByText({
        netWorthTimeList: new_dates,
        netWorthValueTextList: new_txts,
        investName: this.dataFrom.investName,
        strategyId: this.dataFrom.strategyId,
        strategyName: this.dataFrom.strategyName,
        userId: this.dataFrom.userId,
        strategyNetWorthStyle: this.dataFrom.strategyNetWorthStyle,
      }).then(res => {
        if(res.code == 0) {
          this.$notify({
            message: res.body,
            type: 'success',
            duration: 2000
          })
          this.visible = false
          this.$emit('closeOpen')
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.enternetValueOpen {
  ::v-deep .el-dialog__header {
    .tit {
      font-size: 18px;
      color: #303133;
    }
  }
  .tips {
    padding: 10px 0;
    color: #1890FF;
  }
  ::v-deep .el-dialog__body { min-height: 360px; max-height: 60vh; overflow-y: auto; padding-top: 0px; }
  .addNetworth-line {
    padding: 0 16px;
    .el-icon-close {
      cursor: pointer;
      color: #ff561b;
      font-weight: bold;
      font-size: 16px;
      margin-left: 20px;
    }
    .el-icon-plus {
      cursor: pointer;
      color: #409EFF;
      font-weight: bold;
      font-size: 16px;
      margin-left: 10px;
    }
    .error-border {
      ::v-deep input { border: 1px solid red; }
    }
  }
  .el-radio-group { margin-bottom: 24px; }
  .addNetworth-line + .addNetworth-line {
    margin-top: 12px;
  }
  .txtChunk {
    display: flex;
    justify-content: space-around;
    .txt-chunk {
      min-width: 100px;
      width: 60%;
      display: flex;
      flex-direction: column;
      align-items: center;
      span {text-align: center;font-weight: bold;}
      ::v-deep .el-textarea {
        margin-top: 10px;
      }
    }
  }
}
</style>
